<?php
namespace bee;

class tree
{ public $value;
  public $key;
  /** 
   * @var array
   */
  public $children;

  /** 
   * @var tree
   */
  protected $parent;
  
  public function __construct($item)
  { $this->value = $item;
    $this->children = array();
  }
  
  /** 
   * @param $item
   * @param $key
   * @return tree
   */
  public function addChild($item, $key)
  { $obj = new tree($item);
    if($key)
    { $obj->key = $key;
    }
    return $this->setChild($obj);
  }
  /**
   * 
   * @param unknown_type $item
   * @param unknown_type $key
   * @return tree
   */
  public function setNode($item, $key)
  { if($node = $this->getNodeByKey($key))
    { $node->value = $item;
      return $node;
    }
    return false;
  }
  
  
  /** 
   * @param tree $item
   * @param unknown_type $key
   * @return tree
   */
  public function setChild(tree &$item)
  { if($item->key)
    { $node = $this;
      while($node->parent)
      { $node = $node->parent;
      }
      if($node->getNodeByKey($item->key))
      { return false;
      }
      $this->children[$item->key] = $item;
    } else
    { $this->children[] = $item;
      $key = array_search($item, $this->children);
      $item->key = $key;
    }
    $item->parent = $this;
    return $item;
  }
  
  /**
   * 
   * @param unknown_type $key
   * @return tree
   */
  public function getNodeByKey($key)
  { if($this->key === $key)
    { return $this;
    }
    foreach($this->children as $v)
    { if($back = $v->getNodeByKey($key))
      { return $back; 
      } 
    }
    return false;
  }
  
  /**
   * 
   * @param unknown_type $key
   * @param bool $forceSubtree
   * @return bool
   */
  public function deleteNode($key, $forceSubtree = false)
  { if($node = $this->getNodeByKey($key))
    { if(count($node->children, false) && !$forceSubtree)
      { return false;
      } else 
      { unset($node->parent->children[$key]);
        unset($node);
      }
    } else
    { return false;
    }
  }
  
}